package com.heima.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.pojo.User;
import com.heima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/findAll")
    public String findAll(){
        String userStr = (String)redisTemplate.boundValueOps("userAll").get();
        if (!StringUtils.hasLength(userStr)){
            System.out.println("从数据库查找");
            List<User> list = userService.findAll();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                userStr = objectMapper.writeValueAsString(list);
                redisTemplate.boundValueOps("userAll").set(userStr);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return userStr;
    }

}
